package controllers

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"purchase-mall/dao/redis"
	"purchase-mall/models"
	"purchase-mall/services"
	"purchase-mall/utils"
	"time"
)

// AccessTotalHandler 获取昨日访问总量
func AccessTotalHandler(c *gin.Context) {
	//默认昨天
	var endTimeMaps = make(map[string]int64)
	endTimeMaps[time.Now().AddDate(0, 0, -1).Format("2006-01-02")] = utils.YesterdayTime()

	//先从redis查
	data, err := GetRedisAccessTotal(endTimeMaps)
	if err == nil {
		ResponseSuccess(c, data)
		return
	}

	data, err = services.GetAccessTotalService(endTimeMaps)
	if err != nil {
		zap.L().Error("services.GetAccessTotalService() failed", zap.Error(err))
		ResponseError(c, CodeServerBusy)
		return
	}
	ResponseSuccess(c, data)
}

// AccessTotalWeekHandler 获取7日访问总量
func AccessTotalWeekHandler(c *gin.Context) {
	//one week (6 day not today)
	//-5~-1
	var endTimeMaps = make(map[string]int64)
	for i := -5; i <= -1; i++ {
		endTimeMaps[time.Now().AddDate(0, 0, i-1).Format("2006-01-02")] = utils.RandomTime(i)
	}
	endTimeMaps[time.Now().AddDate(0, 0, -1).Format("2006-01-02")] = utils.YesterdayTime() //昨天

	//先从redis查
	data, err := GetRedisAccessTotal(endTimeMaps)
	if err == nil {
		services.BubbleAccessTotal(data)
		ResponseSuccess(c, data)
		return
	}

	data, err = services.GetAccessTotalService(endTimeMaps)
	if err != nil {
		zap.L().Error("services.GetAccessTotalService() failed", zap.Error(err))
		ResponseError(c, CodeServerBusy)
		return
	}
	ResponseSuccess(c, data)
}

func GetRedisAccessTotal(endTimeMaps map[string]int64) ([]*models.AccessTotalInfo, error) {
	data := make([]*models.AccessTotalInfo, 0, len(endTimeMaps))
	for k, _ := range endTimeMaps {
		var d = models.AccessTotalInfo{Time: k}
		err, cdnAccessTotal := redis.GetAccessTotal(fmt.Sprintf("%s|%s", k, "cdn_access_total"))
		if err != nil {
			return nil, err
		}
		d.CdnTotalNum = cdnAccessTotal

		err, gatewayAccessTotal := redis.GetAccessTotal(fmt.Sprintf("%s|%s", k, "gateway_access_total"))
		if err != nil {
			return nil, err
		}
		d.GatewayTotalNum = gatewayAccessTotal

		err, upstreamAccessTotal := redis.GetAccessTotal(fmt.Sprintf("%s|%s", k, "upstream_access_total"))
		if err != nil {
			return nil, err
		}
		d.UpstreamTotalNum = upstreamAccessTotal

		data = append(data, &d)
	}

	return data, nil
}
